import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ConcurrentHashMap;

public class Dispatcher implements Runnable
{
    private int port;
    
    public Dispatcher(int port)
    {
        this.port = port;
    }
    
    @Override
    public void run()
    {
        try
        {
            ServerSocket soc = new ServerSocket(port);
            while (true)
            {
                Socket csoc = soc.accept();
                ComputeNode cn = getIdleCN();
                Logger.log("Connection from " + csoc.getInetAddress() + " to local port " + port + " dispatched to " + cn.hostname);
                new Thread(new TCPProxy(cn, csoc)).start();
            }
        }
        catch (IOException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }
    
    private ComputeNode getIdleCN()
    {
        ConcurrentHashMap<String, ComputeNode> computeNodes = Metadata.getInstance().getComputeNodes();
        double min = 1;
        ComputeNode idle = null;
        for (ComputeNode cn : computeNodes.values())
        {
            if (idle == null || min > cn.cpu_percent)
            {
                idle = cn;
                min = cn.cpu_percent;
            }
        }
        
        return idle;
    }
}
